<?php

namespace app\cash\controller\member;
use app\BaseController;

use app\beautiful\model\LevelModel;
use app\beautiful\model\logs\MemberBalanceLogsModel;
use app\beautiful\model\member\MemberBalanceModel;
use app\beautiful\model\member\MemberModel;
use app\beautiful\model\PartnerModel;
use app\beautiful\model\setting\LevelSettingModel;
use app\stores\model\member\MemberLevelModel;
use think\facade\Db;

class Member extends BaseController{

    /**
     * 会员信息
     */
    public function info(){
        $mobile = $this->request->param('mobile');
        $nick_name = $this->request->param('nick_name');

        if(empty($mobile) && empty($nick_name)) return $this->success([]);

        if($mobile) $where[] = ['mobile','like','%'.$mobile.'%'];
        if($nick_name) $where[] = ['nick_name','like','%'.$nick_name.'%'];
        $member = MemberModel::where($where)->find();
        if($member){
            //股东
            $p_where['shop_id'] = $this->request->shopId;
            $p_where['member_id'] = $member['member_id'];
            $p_where['status'] = 1;
            $p_where['is_delete'] = 0;
            $partner = PartnerModel::info($p_where);
            $member['partner_type'] = $partner?$partner['type']:null;
            //是否是会员
            $mL_model = new MemberLevelModel();
            $ml = $mL_model->getById(['member_id'=>$member['member_id'],'shop_id'=>$this->request->shopId,'is_delete'=>0]);
            $member['is_vip'] = $ml?1:0;
            //等级
            $level_id = getMemberLevel($member['member_id'],$this->request->shopId);
            $level = LevelModel::find($level_id);
            $member['level_name'] = null;
            $member['discount'] = 10;
            if($level){
                $member['level_name'] = $level['name'];
                $member['discount'] = $level['type']==1?$level['discount']:$level['discount_force'];
            }
            //余额
            $member['balance'] = MemberBalanceModel::where([

                    ['shop_id','=',$this->request->shopId],

                    ['member_id','=',$member['member_id']],

                    ['valid_bg_time','<=',$this->request->time()]

                ])->sum('remain_balance') ?? 0;

            //充值金额（需要减去退款）
            $member['recharge_balance'] = MemberBalanceLogsModel::where(['shop_id'=>$this->request->shopId,'member_id'=>$member['member_id'],'type'=>1])
                ->whereNotIn('type_id',[23,24,27])
                ->sum('balance');
            //赠送
            $member['recharge_give_balance'] = MemberBalanceLogsModel::where(['shop_id'=>$this->request->shopId,'member_id'=>$member['member_id'],'type'=>1])->sum('give_balance');

        }

        return $this->success($member);
    }

    /**
     * 添加会员
     */
    public function add(){
        $nick_name = $this->request->param('nick_name');
        $mobile = $this->request->param('mobile');
        $sex = $this->request->param('sex/d',1);
        $birthday = $this->request->param('birthday');
        $level_id = $this->request->param('level_id/d',0);
        $remarks = $this->request->param('remarks');

        if(empty($nick_name)) return $this->error('客户姓名不能为空');
        if(empty($mobile)) return $this->error('客户手机号不能为空');

        Db::startTrans();
        try{
            $member = MemberModel::where(['mobile'=>$mobile])->find();
            if(empty($member)){
                if($birthday){
                    $data['birthday_year'] = date('Y',strtotime($birthday));
                    $data['birthday_month'] = date('m',strtotime($birthday));
                    $data['birthday_day'] = date('d',strtotime($birthday));
                }
                $data['nick_name'] = $nick_name;
                $data['mobile'] = $mobile;
                $data['sex'] = $sex;
                $data['from_type'] = 2;
                $data['remarks'] = $remarks;
                $data['add_time']=request()->time();
                $data['add_ip']=request()->ip();
                $member['member_id'] = MemberModel::insertGetId($data);
            }
            $mL_model = new MemberLevelModel();
            $ml = $mL_model->getById(['member_id'=>$member['member_id'],'shop_id'=>$this->request->shopId,'is_delete'=>0]);
            if($ml) return $this->success('该用户已经是会员了');
            if($level_id>0){
                $level = LevelModel::where(['level_id'=>$level_id,'shop_id'=>$this->request->shopId,'is_delete'=>0])->find();
                if($level) return $this->success('等级不存在');
            }
            $l_data['shop_id'] = $this->request->shopId;
            $l_data['member_id'] = $member['member_id'];
            $l_data['level_id'] = $level_id;
            $l_data['add_time']=request()->time();
            $l_data['add_ip']=request()->ip();

            MemberLevelModel::insertGetId($l_data);

            Db::commit();
        }catch(\Exception $e){

            Db::rollback();

            return $this->error($e->getMessage());

        }
        return $this->success('添加成功');

    }
    /**
     * 获取会员等级列表
    */
    public function levelList(){
        $select_setting = LevelSettingModel::where(['shop_id'=>$this->request->shopId,'is_selected'=>1])->find();
        $level['count'] = 0;
        $level['list'] = [];
        if($select_setting && $select_setting['type']>0){
            $level = LevelModel::list(['shop_id'=>$this->request->shopId,'type'=>$select_setting['type'],'is_delete'=>0],['vip_level'=>'asc'],$this->request->page,$this->request->limit,'level_id,name');
        }
        $level['count'] += 1;
        $level['list'][] = [
            'level_id'=>0,
            'name'=>'普通会员'
        ];
        return $this->success($level);
    }
    /**
     * 获取会员列表
     */
    public function list(){
        $search = $this->request->param('search');
        if(!empty($search)) $where['search'] = $search;
        $where['shop_ids'] = [$this->request->shopId];
        $field = "m.nick_name,m.face,m.mobile,ml.shop_id,ml.member_id,ml.level_id,s.name as shop_name,sd.logo,l.name as level_name,l.discount,l.discount_force,l.type";
        $return = MemberLevelModel::list($where,['ml.member_id'=>'asc'],$this->request->page,$this->request->limit,$field);
        return $this->success($return);
    }
}

